package com.tool_stdy.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by yan_li on 2016/1/29.
 */
public class DeathThreadTest implements Runnable {
    static Lock lock1 = new ReentrantLock();
    static Lock lock2 = new ReentrantLock();
     int a;
     int b;
    public DeathThreadTest(int a,int b){
        this.a=a;
        this.b=b;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"==>"+a);
            if(a==1){
                try {
                    lock1.lockInterruptibly();
                    Thread.sleep(500);
                    lock2.lockInterruptibly();
                    System.out.println(a+"-->"+b);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("release");
                    lock1.unlock();
                    lock2.unlock();
                }
            }else {
                try {
                    lock2.lockInterruptibly();
                    Thread.sleep(500);
                    lock1.lockInterruptibly();
                    System.out.println("else :"+a+"-->"+b);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println("release");
                    lock1.unlock();
                    lock2.unlock();
                }
            }
    }

    public static void main(String[] args) throws InterruptedException {
        DeathThreadTest tt = new DeathThreadTest(1,2);
        Thread t1= new Thread(tt);
        t1.start();
        Thread.sleep(200);
        tt.a=2;
        Thread t2 = new Thread(tt);
        t2.start();
        t1.join();
        t2.join();
        System.out.println("over");
    }
}
